<script setup>
import { useRoute } from 'vue-router'
import { login } from '@/api/auth'
import { setToken } from '@/assets/js/auth'
import { ElMessage } from 'element-plus';
import router from '@/router';
import { HOME } from '@/router/routeMap'
import LoginView from '@/views/login/index.vue'
import useUserStore from '@/store/user';
import CenterContainer from '@/components/CenterContainer.vue';
import useApiCallback from '@/hooks/useApiCallback'

const userStore = useUserStore()
const route = useRoute()

const [handleLogin, isLoading] = useApiCallback(login)
const onClickLogin = async ({ username, password }) => {
  const result = await handleLogin({ username, password })
  if (result.code === 0) {
    ElMessage.success(result.message)
    const { token, ...userinfo } = result.data
    setToken(token)
    userStore.$patch({ isLogined: true, userinfo })
    router.push(route.params.redirect || HOME)
  }
}
</script>

<template>
  <CenterContainer :offsetLeft="-20" :offsetTop="-40">
    <LoginView @clickLogin="onClickLogin" :isLoading="isLoading" />
  </CenterContainer>
</template>
